package com.aabte.auth.account.infrastructure;

import com.aabte.auth.account.domain.model.Password;
import com.aabte.auth.account.domain.service.PasswordService;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
public class PasswrodServiceImpl implements PasswordService {

    public static final Charset CHARSET = StandardCharsets.UTF_8;
    public static final String ALGORITHM = "MD5";

    @Override
    public Password encryption(String text) {
        MessageDigest instance;
        try {
            instance = MessageDigest.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException("algorithm not found. algorithm: " + ALGORITHM);
        }
        instance.update(text.getBytes(CHARSET));
        byte[] digest = instance.digest();
        return new Password(toHexString(digest));
    }

    public static String toHexString(byte[] ba) {
        StringBuilder builder = new StringBuilder();

        for (byte b : ba) {
            String s = Integer.toHexString(b & 255);
            if (s.length() == 1) {
                builder.append('0');
            }

            builder.append(s);
        }

        return builder.toString();
    }

}
